package xyz.zhno.project.commons.sentinel.block;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import xyz.zhno.project.commons.core.dto.ResultError;
import xyz.zhno.project.commons.core.exception.ProjectExceptionCodeEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局限流处理
 * @author zh_o
 * @date 2020-11-01
 */
@Slf4j
@Component
public class GlobalBlockException implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.warn("{} 被限流", e.getRule().getResource());
        ResultError res = ResultError.builder()
                .code(ProjectExceptionCodeEnum.REQUEST_BLOCK.getCode())
                .message(ProjectExceptionCodeEnum.REQUEST_BLOCK.getMessage())
                .build();
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        JSON parse = JSONUtil.parse(res);
        response.getWriter().write(parse.toStringPretty());
    }
}

